﻿using Microsoft.AspNetCore.Http;

namespace Micro.Extensions.Utilities
{
    public static class HttpContextAccessorExtensions
    {
        /// <summary>
        /// 获取HTTP Header 值
        /// </summary>
        /// <param name="httpContextAccessor">httpContextAccessor</param>
        /// <param name="key">header key</param>
        /// <returns>如果获取失败，则返回空字符串</returns>
        public static string TryGetHeaderValue(this IHttpContextAccessor httpContextAccessor, string key)
        {
            string returnVal = string.Empty;
            var headers = httpContextAccessor?.HttpContext?.Request?.Headers;
            if (headers != null)
            {
                if (headers.TryGetValue(key, out var value))
                    returnVal = value;
            }

            return returnVal;
        }
    }
}
